package com.liuyjy.base.common.result;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * @Author liuyjy
 * @Date 2020/10/13 10:39
 * @Description: 请求返回定义
 **/
@ApiModel(description = "请求返回体封装对象", value = "请求返回体封装对象")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class Result<T> implements Serializable {

    public static final String SUCCESS = "success";
    public static final String ERROR = "error";

    @ApiModelProperty(value = "错误码", name = "code", required = true)
    private String code;

    @ApiModelProperty(value = "消息", name = "msg", required = true)
    private String msg;

    @ApiModelProperty(value = "返回结果", name = "data")
    private T data;


    @ApiModelProperty(value = "结果状态", name = "state")
    private String state;


    private Result(ResultCodeInterface codeInterface, T data) {
        this.code = codeInterface.getCode();
        this.msg = codeInterface.getMsg();
        this.data = data;
        this.state = code.equals(ResultCodeEnum.SUCCESS.code) ? SUCCESS : ERROR;
    }

    private Result(String code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.state = code.equals(ResultCodeEnum.SUCCESS.code) ? SUCCESS : ERROR;
    }

    /**
     * 正常返回
     *
     * @param data 数据
     * @return <T>Result<T>
     */
    public static <T> Result<T> generateSuccess(T data) {
        return generate(ResultCodeEnum.SUCCESS, data);
    }

    /**
     * 正常返回
     *
     * @return <T>Result<T>
     */
    public static <T> Result<T> generateSuccess() {
        return generate(ResultCodeEnum.SUCCESS);
    }

    /**
     * 异常返回
     *
     * @return <T>Result<T>
     */
    public static <T> Result<T> generateError(String msg) {
        return generate("1001", msg);
    }


    public static <T> Result<T> generate(ResultCodeInterface e, String msg) {
        return generate(e.getCode(), e.getMsg() + ":" + msg);
    }

    public static <T> Result<T> generate(String code, String message) {
        return generate(code, message, null);
    }

    public static <T> Result<T> generate(ResultCodeInterface e) {
        return generate(e.getCode(), e.getMsg(), null);
    }

    public static <T> Result<T> generate(String code, String message, T data) {
        return new Result<T>(code, message, data);
    }

    public static <T> Result<T> generate(ResultCodeInterface e, T data) {
        return new Result(e, data);
    }


    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}
